package main;

import game.Game;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.MemoryImageSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintStream;
import java.net.URI;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.Timer;

/*
 * Quiz.java
 *
 * Created on May 22, 2009, 8:02:02 PM
 */

/**
 *
 * @author Vinay
 */
public class Quiz extends javax.swing.JInternalFrame {

    Game g = new Game();
    int index=0,size=0;
    Vector<String> data=new Vector();
    String ques[];
    boolean corrAns[],userAns[],userTimeOut[],ansFlag=false;
    boolean finished;

    int totalTime=30,secs = totalTime, timeTaken=0;
    Timer time = new Timer(1000, new TimeListener());

	/** The amount of time the player took to come up with the answer. */
	int playerThinkTime;

	/** The amount of money, in dollars, that the subject gets for a correct
	 answer. */
	final double CORRECT_MONEY = 0.25;

    /** Creates new form Quiz */
    public Quiz() {
        initComponents();
        initData(false);
        
        javax.swing.plaf.InternalFrameUI ui = this.getUI();
        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation(screenSize.width/2-400, screenSize.height/2-300);
        this.setVisible(true);
        hideMouse();
        addMouseListener( new Quiz.CheckMouse() ) ;

        //Initialising the screen to the first question
        dispQues();

        time.start();
        updateTimeLabel();
    }
    
    public Quiz(String game) {
        initComponents();
        initData(false);
        
        javax.swing.plaf.InternalFrameUI ui = this.getUI();
        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation(screenSize.width/2-400, screenSize.height/2-300);
        this.setVisible(true);

        g.runner.addMouseListener( new Quiz.CheckMouse() ) ;
        addMouseListener( new Quiz.CheckMouse() ) ;
		this.getGlassPane().addMouseListener(new Quiz.CheckMouse());
		hideMouse();

        //Initialising the screen to the first question
        dispQues();

        time.start();
		updateTimeLabel();
    }

	/**
	 * Updates the time label at the top.
	 */
	void updateTimeLabel() {
		int min = secs/60;
        int sec = secs%60;
        lblTime.setText(min+":"+((sec<10)?"0":"")+sec);
	}

    /*To initialise quiz data in arrays from file*/
    void initData(boolean def) {
        try {
            URI name;
//            if(def)
//                name = new URI(this.getClass().getResource("quiz/default_quiz.csv").toString());
//            else
//                name = new URI(this.getClass().getResource("quiz/"+g.currGame+"_quiz.csv").toString());

            File f = new File("quiz/"+g.currGame+"_quiz.csv");
            if(!f.exists())
                f = new File("quiz/default_quiz.csv");

//            File f = new java.io.File(name);
            BufferedReader br = new BufferedReader(new FileReader(f));
            String line="";

            //Capturing all data in memory
            br.readLine();
            while((line = br.readLine()) != null) {
                data.add(line);
            }
            br.close();
            size = data.size();

            //declaring arrays with size
            ques = new String[size];
            corrAns = new boolean[size];
            userAns = new boolean[size];
            userTimeOut = new boolean[size];

            //filling values for question and correcta answer arrays
            for(int i=0; i<size; i++) {
                String dataPart[] = data.get(i).split(",");
                ques[i] = dataPart[0];
                if(dataPart[1].equals("1"))
                    corrAns[i] = true;
                else
                    corrAns[i] = false;
            }
        }
        catch(FileNotFoundException ex) {
            initData(true);
        }
        catch(Exception ex) {
            ex.printStackTrace();
            g.logError(ex);
        }
    }

    /*To display question on screen*/
    void dispQues() {
        lblTitle.setText("Question "+(index+1));
        lblImg.setIcon(null);
        lblImg.repaint();
        lblAns.setText("");
        lblQ.setText(ques[index]);
        lblYes.setVisible(true);
        lblNo.setVisible(true);
		playerThinkTime = 0;
    }

    void dispQuesIfExists() {
        index++;
        if(index<size) { //There are still Qs to be displayed
            ansFlag=false;
            dispQues();
        } else {
            finished=true;
            lblAns.setText(null);
            lblTitle.setText(null);
            lblForm.setText(null);
            lblImg.setVisible(false);
            lblYes.setVisible(false);
            lblNo.setVisible(false);

			int numCorrect = 0;
			for(int i=0; i<corrAns.length; i++) {
                if(!userTimeOut[i] && userAns[i] == corrAns[i])
                    numCorrect++;
            }
			double moneyWon = numCorrect * CORRECT_MONEY;
			
            String logText = g.playerId + ",,\"Quiz," + g.currGame+"\",1,1,"
				+ String.format ("$%.2f",moneyWon) + ",";
            g.writeLog(logText);

            lblQ.setText("Starting the game in a few moments ...");
            secs=-4;
        }
    }

	void writeGameLog (String s) {
		try {
			FileOutputStream fout = new FileOutputStream("logs/Quiz_log.csv", true);
			PrintStream p = new PrintStream(fout);
			p.println(s);
		}
		catch(Exception ex) {
			ex.printStackTrace();
			g.logError(ex);
		}
	}

    void dispAns() {
        lblYes.setVisible(false);
        lblNo.setVisible(false);
        ansFlag=true;
        String strCorr="";
        if(corrAns[index])
            strCorr = "Yes";
        else
            strCorr = "No";

		int correct;
        if(corrAns[index]==userAns[index]) { //Answer is correct
            lblAns.setText("Correct!");
            lblImg.setIcon(new ImageIcon(this.getClass().getResource("/images/greenTick.png")));
            g.totalMoneyWon += CORRECT_MONEY;
			correct = 1;
        } else { //Answer is wrong
            lblAns.setText("Wrong! Correct answer is "+strCorr+".");
            lblImg.setIcon(new ImageIcon(this.getClass().getResource("/images/redCross.png")));
			correct = 0;
        }

		writeGameLog (g.playerId + "," + playerThinkTime + "," + g.currGame
			+ "," + (index+1) + "," + correct);

        secs=0;
    }

    /*To display summary on screen*/
    void dispSummary() {
        lblTitle.setText("Summary");
        int fsize=20;
        String color="",img="",strCorr="",strUser="";
        String strPane = "<center><table border='0'><font size='"+fsize+"' face='Calibri'><tr><td><b>Question</b></td><td><b>Correct  Ans.</b></td><td><b>Your Ans.</b></td><td></td></tr>";
        for(int i=0; i<size; i++) {
            //Set bgcolor to green of answers match else set it to red
            if(userAns[i]==corrAns[i]) {
                color="GREEN";
            } else {
                color="RED";
            }
            //Setting text
            if(corrAns[i])
                strCorr = "Yes";
            else
                strCorr = "No";
            if(userAns[i])
                strUser = "Yes";
            else
                strUser = "No";

            strPane += "<tr><td bgcolor='"+color+"'>"+ques[i]+"</td><td align='center' bgcolor='"+color+"'>"+strCorr+"</td><td align='center' bgcolor='"+color+"'>"+strUser+"</td><td></td></tr>";
        }
        strPane+="</font></table></center>";
        System.out.println(strPane);
        //edpData.setText(strPane);
        //edpData.repaint();
        lblYes.setVisible(false);
        lblNo.setVisible(false);
    }

    private void hideMouse() {
        int[] pixels = new int[16 * 16];
        Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
        Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisibleCursor");
		this.getGlassPane().setCursor(transparentCursor);
		this.getGlassPane().setVisible(true);
		setCursor (transparentCursor);
        g.runner.setCursor(transparentCursor);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblForm = new javax.swing.JLabel();
        lblTitle = new javax.swing.JLabel();
        lblYes = new javax.swing.JLabel();
        lblNo = new javax.swing.JLabel();
        lblQ = new javax.swing.JLabel();
        lblAns = new javax.swing.JLabel();
        lblImg = new javax.swing.JLabel();
        lblTime = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(null);

        lblForm.setFont(new java.awt.Font("Calibri", 1, 28));
        lblForm.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblForm.setText("Quiz");

        lblTitle.setFont(new java.awt.Font("Calibri", 1, 26));
        lblTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTitle.setText("Question 1");

        lblYes.setFont(new java.awt.Font("Calibri", 1, 24));
        lblYes.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblYes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/redYes.png"))); // NOI18N

        lblNo.setFont(new java.awt.Font("Calibri", 1, 24));
        lblNo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblNo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/greenNo.png"))); // NOI18N

        lblQ.setFont(new java.awt.Font("Calibri", 1, 30));
        lblQ.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblQ.setText("jLabel1");
        lblQ.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        lblAns.setFont(new java.awt.Font("Calibri", 1, 28));
        lblAns.setForeground(new java.awt.Color(51, 102, 255));
        lblAns.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblAns.setText("jLabel1");

        lblImg.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        lblTime.setFont(new java.awt.Font("Calibri", 1, 36));
        lblTime.setForeground(new java.awt.Color(153, 102, 0));
        lblTime.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/hrGlass.png"))); // NOI18N
        lblTime.setText("3:00");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(100, 100, 100)
                .add(lblYes, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 233, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 119, Short.MAX_VALUE)
                .add(lblNo)
                .add(115, 115, 115))
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lblAns, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(lblQ, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(lblImg, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lblTitle, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(lblForm, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(lblTime, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(lblTime, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(3, 3, 3)
                .add(lblForm, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 27, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(45, 45, 45)
                .add(lblTitle, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(lblImg, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(lblQ, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 132, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(7, 7, 7)
                .add(lblAns, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 47, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(lblYes)
                    .add(lblNo))
                .add(92, 92, 92))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
     @Override
    public synchronized void addMouseListener(MouseListener l) {
        super.addMouseListener(l);
    }

    /*MouseListener class for capturing left and right clicks*/
    class CheckMouse implements MouseListener{
        public void mousePressed(MouseEvent e) { hideMouse(); }
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        public void mouseClicked(MouseEvent e) {
			// Don't do anything if we're displaying the answer.
			if (ansFlag) return;

			int modifiers = e.getModifiers();
            if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
//                index++;
//                if(lblTitle.getText().equals("Summary")) { //Summary has been displayed. Close quiz
//                    setVisible(false);
//                    g.free=true;
//                } else if(index==size) { //All questions have been displayed
//                    userAns[index-1]=true;
//                    dispSummary();
//                } else { //There are still questions to be displayed
//                    userAns[index-1]=true;
//                    dispQues();
//                }
                if(finished) {

                }
                else if(ansFlag) { //Result is on display
                    dispQuesIfExists();
                } else { //Question is on display
                    userAns[index]=true;
                    dispAns();
                }
            }
            if ((modifiers & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK) {}
            if ((modifiers & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK) {
//                index++;
//                if(lblTitle.getText().equals("Summary")) { //Summary has been displayed. Close quiz
//                    setVisible(false);
//                    g.free=true;
//                } else if(index==size) { ////All questions have been displayed
//                    userAns[index-1]=false;
//                    dispSummary();
//                } else { //There are still questions to be displayed
//                    userAns[index-1]=false;
//                    dispQues();
//                }
                if(finished) {

                }
                else if(ansFlag) { //Result is on display
                    dispQuesIfExists();
                } else { //Question is on display
                    userAns[index]=false;
                    dispAns();
                }
            }
        }
    }

    class TimeListener implements ActionListener {
    	public void actionPerformed(ActionEvent e) {
    		playerThinkTime++;
			secs--;
            if(secs>=0) {
                updateTimeLabel();
            }
            if(secs==0) {
                lblAns.setText(null);
                lblTitle.setText(null);
                lblYes.setVisible(false);
                lblNo.setVisible(false);
                lblQ.setText("Sorry, your time is up !!");
                userTimeOut[index]=true;
                //dispQuesIfExists();
            }
            if(secs==-4) {
                secs=30;
				updateTimeLabel();
                dispQuesIfExists();
            }
            if(secs==-10) {
                time.stop();
                // End quiz.
				try {
					getGlassPane().setVisible(false);
                    setVisible(false);
                    g.free=true;
                } catch(Exception ex) {
                    ex.printStackTrace();
                    g.logError(ex);
                }
            }
    	}

    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JFrame main = new JFrame();
                    JDesktopPane dPane = new JDesktopPane();
                    Quiz frame = new Quiz();
                    main.setSize(820, 620);
                    dPane.add(frame);
                    main.add(dPane);
                    main.setVisible(true);
                    dPane.setVisible(true);
                    frame.setSelected(true);
                    frame.setVisible(true);
                } catch(Exception ex) {
                    ex.printStackTrace();
                };
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel lblAns;
    private javax.swing.JLabel lblForm;
    private javax.swing.JLabel lblImg;
    private javax.swing.JLabel lblNo;
    private javax.swing.JLabel lblQ;
    private javax.swing.JLabel lblTime;
    private javax.swing.JLabel lblTitle;
    private javax.swing.JLabel lblYes;
    // End of variables declaration//GEN-END:variables
}